<?php

namespace App;

use Illuminate\Support\Facades\DB;
use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\WebSocket\MessageComponentInterface;

class MyCustomWebSocketHandler implements MessageComponentInterface
{
    protected $clients = [];
    protected $messagesCount = 0;
    protected $errorsCount = 0;

    public function __construct()
    {
        // 初始化客户端列表
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $connection)
    {
        // 当连接打开时的处理逻辑
        echo "新连接! ({$connection->resourceId})\n";
        $this->clients->attach($connection);

        // 记录统计信息
        $this->recordStatistics();
    }

    public function onClose(ConnectionInterface $connection)
    {
        // 当连接关闭时的处理逻辑
        echo "Connection {$connection->resourceId} has disconnected\n";
        $this->clients->detach($connection);

        // 记录统计信息
        $this->recordStatistics();
    }

    public function onError(ConnectionInterface $connection, \Exception $e)
    {
        // 当发生错误时的处理逻辑
        echo "An error has occurred: {$e->getMessage()}\n";
        $this->errorsCount++;
        $connection->close();

        // 记录统计信息
        $this->recordStatistics();
    }

    public function onMessage(ConnectionInterface $connection, MessageInterface $msg)
    {
        // 当接收到消息时的处理逻辑
        $numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $connection->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        // 可以在这里处理消息并发送响应
        $connection->send("Server received: {$msg}");

        // 增加消息计数
        $this->messagesCount++;

        // 记录统计信息
        $this->recordStatistics();
    }

    private function recordStatistics()
    {
        DB::table('websockets_statistics_entries')->insert([
//            'timestamp' => now(),
            'peak_connection_count' => count($this->clients),
            'websocket_message_count' => $this->messagesCount,
            'api_message_count' => $this->errorsCount,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}

